<template>
  <div class="body">
    <div class="ser_div">
      <el-row>
        <el-col>
          <el-row style="display: flex; align-items: center">
            <el-col :span="8" style="text-align: center"> 客户</el-col>
            <el-col :span="16">
              <el-input
                v-model="ser.customer_name"
                placeholder="请输入客户名称"
              ></el-input>
            </el-col>
          </el-row>
        </el-col>
        <el-col>
          <el-row style="display: flex; align-items: center">
            <el-col :span="8" style="text-align: center"> 业务员</el-col>
            <el-col :span="16">
              <el-select
            v-model="ser.account_executive_id"
            filterable
            placeholder="请选择业务员"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in UserList"
              :key="index"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
             
            </el-col>
          </el-row>
        </el-col>
        <el-col>
          <el-row style="display: flex; align-items: center">
            <el-col :span="8" style="text-align: center"> 客户余额</el-col>
            <el-col :span="16">
              <el-input
                v-model="ser.balance"
                placeholder="请输入客户名称"
              ></el-input>
            </el-col>
          </el-row>
        </el-col>
        <el-col>
          <el-row style="display: flex; align-items: center">
            <el-col :span="8" style="text-align: center"> 余额状态</el-col>
            <el-col :span="16">
              <el-select
                v-model="ser.balance_status"
                filterable
                placeholder="请选择余额状态"
                style="width: 100%"
              >
                <el-option label="全部" value="0"> </el-option>
                <el-option label="有结余" value="1"> </el-option>
                <el-option label="有欠款" value="2"> </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-col>
        <el-col>
          <el-button
            @click="customer_click(0)"
            icon="el-icon-search"
            class="add_btn"
          >
            搜索</el-button
          >
          <el-button
            @click="customer_clicks"
            icon="el-icon-refresh"
            class="add_btn"
          >
            重置</el-button
          >
          <el-button @click="add_product" icon="el-icon-plus" class="add_btn"
            >新增客户</el-button
          >
        </el-col>
      </el-row>
    </div>
    <el-table
      :data="productList"
      v-loading="loading"
      stripe
      style="width: 100%"
      @sort-change="sortchange"
      border
    >
      <el-table-column prop="customer_name" label="客户名称" width="150">
      </el-table-column>
      <el-table-column prop="contact" label="联系人" width="100">
      </el-table-column>
      <el-table-column label="业务员" width="100">
        <template slot-scope="scope">
          <span
            >{{ scope.row.user?scope.row.user.username:'' }}</span
          >
        </template>
      </el-table-column>
      <el-table-column prop="contact_phone" label="电话" width="120">
      </el-table-column>
      <!-- <el-table-column label="省/市/区" width="300">
        <template slot-scope="scope">
          <span
            >{{ scope.row.provinces }} {{ scope.row.city
            }}{{ scope.row.county }}</span
          >
        </template>
      </el-table-column> -->
      <el-table-column prop="logistics" label="货站" width="100">
         <template slot-scope="scope">
          <span
            >{{ scope.row.logistics }}</span
          >
        </template>
      </el-table-column>
      
      <el-table-column prop="balance" label="余额" sortable="custom" sort-by="balance" :sort-method="sortMethod"   width="200" > 
        <template slot-scope="scope">
          <span :class="scope.row.balance< 0 ? 'red':''">{{ scope.row.balance }}</span>
          <span
            @click="mingxi_get(scope.row.id)"
            style="cursor: pointer; color: cadetblue; padding-left: 5px"
            >充值明细</span
          >
          <span
            @click="mingxi_gets(scope.row.id,scope.row.customer_name)"
            style="cursor: pointer; color: cadetblue; padding-left: 5px"
            >订单明细</span
          >
        </template>
      </el-table-column>
      <el-table-column prop="customer_address" label="详细地址" width="300">
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="300">
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button
            @click="set_product(scope.row)"
            type="text"
            icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button
            @click="set_product_money(scope.row.id, scope.row.balance)"
            type="text"
            icon="el-icon-edit"
            >充值</el-button
          >
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="是否删除这条数据？"
            @confirm="del_product(scope.row)"
          >
            <el-button slot="reference" type="text" icon="el-icon-delete">
              删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        @prev-click="prev"
        @next-click="next"
        :current-page.sync="pagination.page"
        :page-size="pagination.per_page"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="title"
      :visible.sync="isProduct"
      width="30%"
      :close-on-click-modal="false"
      @close="dialog_close"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="客户名称" prop="customer_name">
          <el-input v-model="ruleForm.customer_name"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="ruleForm.contact"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input v-model="ruleForm.contact_phone"></el-input>
        </el-form-item>
        <el-form-item label="物流" prop="logistics">
          <el-input v-model="ruleForm.logistics"></el-input>
          <!-- <el-select
            v-model="ruleForm.logistics_id"
            filterable
            placeholder="请选择物流"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in logisticsCompanyList"
              :key="index"
              :label="item.company_name"
              :value="item.id"
            >
            </el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="省/市/区/县" prop="provinces">
          <el-cascader
            size="large"
            :options="options"
            v-model="selectedOptions"
            @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="customer_address">
          <el-input v-model="ruleForm.customer_address"></el-input>
        </el-form-item>
        <el-form-item label="业务员">
          <el-select
            v-model="ruleForm.account_executive_id"
            filterable
            placeholder="请选择业务员"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in UserList"
              :key="index"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
        style="display: block; text-align: center"
      >
        <el-button @click="dialog_close">取 消</el-button>
        <el-button type="primary" @click="submitadd('ruleForm')"
          >确定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="充值"
      :visible.sync="ismoney"
      width="20%"
      :close-on-click-modal="false"
      @close="close_money"
    >
      <el-row style="display: flex; align-items: center">
        <el-col :span="5"> 金额 </el-col>
        <el-col :span="19">
          <el-input-number
            v-model="push_money"
            :precision="0"
            label="请输入金额"
            style="width: 100%; text-align: left"
          ></el-input-number>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ismoney = false">取 消</el-button>
        <el-button type="primary" @click="push_moneys()">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="充值明细"
      :visible.sync="ismingxi"
      width="50%"
      :close-on-click-modal="false"
      @close="close_money"
    >
      <el-table :data="chongzhilist" stripe style="width: 100%" border>
        <el-table-column prop="customer_name" label="客户名称" width="180">
          <template slot-scope="scope">
            <span>
              {{ scope.row.customer.customer_name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="befor" label="起始金额" width="180">
        </el-table-column>
        <el-table-column prop="amount" label="充值金额" width="180">
        </el-table-column>
        <el-table-column prop="after" label="最终金额" width="180">
        </el-table-column>
        <el-table-column prop="date" label="充值时间 " w idth="180">
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ismingxi = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="订单明细"
      :visible.sync="isdingdan"
      width="65%"
      :close-on-click-modal="false"
      @close="close_money"
    > 
    <el-row>
      <el-col :span="24">
       <el-button style="float:right;" type="primary" size="small" @click="click_order">导出</el-button>
      </el-col>
    </el-row>
      <el-table :data="dingdanlist" stripe style="width: 100%" border>
        <el-table-column prop="befor" label="订单号" width="180">
          <template slot-scope="scope">
            <span>
              {{ scope.row.order && scope.row.order.order_number }}
            </span>
          </template>
        </el-table-column>
       
        
        <el-table-column prop="customer_name" label="客户名称" width="180">
          <template slot-scope="scope">
            <span>
              {{ scope.row.customer.customer_name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="befor" label="起始金额" width="180">
        </el-table-column>
        <el-table-column prop="product_name" label="产品" width="180">
        </el-table-column>
        <el-table-column prop="model_number_name" label="型号" width="180"></el-table-column>
        <el-table-column prop="specification_name" label="规格" width="180"></el-table-column>

        <el-table-column prop="product_num" label="订单数量" width="180">
        </el-table-column>
        <el-table-column prop="amount" label="订单金额" width="180">
        </el-table-column>
        <!-- <el-table-column prop="amount" label="应收金额" width="180">
          <template slot-scope="scope">
            <span>
              {{ scope.row.order && scope.row.order.receivables }}
            </span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="amount" label="已收金额" width="180">
          <template slot-scope="scope">
            <span>
              {{ scope.row.order &&  scope.row.order.received }}
            </span>
          </template>
        </el-table-column> -->
        <el-table-column prop="after" label="最终金额" width="180">
        </el-table-column>
        <el-table-column prop="date" label="交易时间 " w idth="180">
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status!==1"
            @click="koukuan(scope.row.id)"
            type="text"
            >取消扣款</el-button>
          <span v-else>已取消</span>
        </template>
      </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isdingdan = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  deductMoney,
  getCustomerList,
  createCustomer,
  delCustomer,
  topUp,
  getBalanceHistoryList,
  getBalanceHistoryList_exports,
  logisticsCompany
} from "@/api/product/index";
import {getUserList } from '@/api/role/index'
import {
  regionDataPlus,
  CodeToText,
  TextToCode,
} from "element-china-area-data";
export default {
  data() {
    var checkphone = (rule, value, callback) => {
      let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!phoneReg.test(value)) {
        callback(new Error("请输入正确的手机号!"));
      } else {
        callback();
      }
    };
    return {
      loading: true,
      idmoney: "",
      ismoney: false,
      push_money: 0,
      ser: {
        customer_name: "",
        balance:'',
        balance_status: '',
        account_executive_id:''
      },
      title: "",
      isProduct: false,
      productList: [],
      ruleForm: {
        customer_name: "",
        provinces: "",
        city: "",
        county: "",
        logistics:'',
        customer_address: "",
        account_executive_id:"",
        contact: "",
        contact_phone: "",
        remark: "",
        logistics_id:"",
        id: "",
      },
      rules: {
        customer_name: [
          {
            required: true,
            message: "请输入客户名称",
            trigger: "blur",
          },
        ],
      
        // contact_phone: [
        //   {
        //     required: true,
        //     validator: checkphone,
        //     trigger: "blur",
        //   },
        // ],
      },
      options: regionDataPlus,
      selectedOptions: [],
      pagination: {
        per_page: 10,
        page: 1,
      },
      total: 0,
      ismingxi: false,
      chongzhilist: [],
      isdingdan: false,
      dingdanlist: [],
      UserList:[],
      paixu:{
        sort_field:'balance',
        sort_type:'desc'
      },
      customer_id:'',
      customer_name:'',
      logisticsCompanyList:[]
    };
  },
  mounted() {
    this.getlist();
    this.userlist();
  },
  methods: {
    log_isticsCompany(){
      logisticsCompany().then(res=>{
        if(res.code==200){
          this.logisticsCompanyList = res.data
        }
      
      })
    },
    koukuan(id) {
      let obj = {
        finish_product_id: id,
        is_deduct_money: 2
      };
      deductMoney(obj).then((res) => {
          if (res.code == 200) {
            this.$message.success("操作成功~");
            this.mingxi_gets(this.customer_id);
          }
        })
        .catch((e) => {
          console.error(e);
        });
    },
    click_order(){
      this.exports_w()
    },
     // 导出
     exports_w() {
      let data = {
        customer_id:this.customer_id,
        business: "扣款",
        export: 1,
      };
      getBalanceHistoryList_exports(data).then((res) => {
        //创建一个隐藏的a连接，
        const link = document.createElement("a");
        let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
        link.style.display = "none";
        //设置连接
        link.href = URL.createObjectURL(blob);
        link.download = this.customer_name+"的交易明细列表";
        document.body.appendChild(link);
        //模拟点击事件
        link.click();
      });
    },
    sortMethod(a,b){
      console.log(a,b)
    },
    sortchange(column, prop, order ){
      console.log(column)

      // this.paixu.sort_field=column.prop
      if(column.order=='descending'){
        this.paixu.sort_type='desc'
      }else{
        this.paixu.sort_type='asc'
      }
      // this.paixu.sort_field=column.prop
      getCustomerList({...this.paixu,...this.pagination}).then((res) => {
        if (res.code == 200) {
          this.productList = res.data.data;
          this.total = res.data.total;
          this.loading = false;
        }
      });
    },
    mingxi_get(id) {
      let obj = {
        business: "余额充值",
        customer_id: id,
      };
      getBalanceHistoryList(obj).then((res) => {
        if (res.code == 200) {
          this.chongzhilist = res.data.data;
          this.ismingxi = true;
        }
      });
    },
    mingxi_gets(id,name) {
      let obj = {
        business: "扣款",
        customer_id: id,
      };
      this.customer_name=name
      this.customer_id=id
      getBalanceHistoryList(obj).then((res) => {
        if (res.code == 200) {
          this.dingdanlist = res.data.data;
          this.isdingdan = true;
        }
      });
    },
    close_money() {
      this.push_money = 0;
    },
    push_moneys() {
      let obj = {
        id: this.idmoney,
        balance: this.push_money,
      };
      topUp(obj).then((res) => {
        if (res.code == 200) {
          this.ismoney = false;
          this.$message.success("提交成功");
          this.getlist();
        }
      });
    },
    set_product_money(id, money) {
      this.idmoney = id;
      // this.push_money=money
      this.ismoney = true;
    },
    del_product(row) {
      console.log("ww");
      delCustomer({
        id: row.id,
        is_del: 1,
      }).then((res) => {
        if (res.code == 200) {
          this.isProduct = false;
          this.$message.success("提交成功");
          this.getlist();
        }
      });
    },
    dialog_close() {
      this.ruleForm = {
        customer_name: "",
        provinces: "",
        city: "",
        county: "",
        customer_address: "",
        account_executive_id:"",
        contact: "",
        contact_phone: "",
        remark: "",
        logistics:"",
        id: "",
      };
      // this.isProduct=falses
      this.selectedOptions = [];
      console.log(this.ruleForm);
    },
    handleChange(value) {
      console.log(value);
      let position = `${CodeToText[value[0]]}/${CodeToText[value[1]]}/${
        CodeToText[value[2]]
      }`;
      console.log(position);

      let arry = position.split("/");

      if (arry[0] == "全部") {
        this.ruleForm.provinces = "";
        this.ruleForm.city = "";
        this.ruleForm.county = "";
      }
      if (arry[0] != "全部" && arry[1] == "全部") {
        this.ruleForm.provinces = arry[0];
        this.ruleForm.city = "全部";
        this.ruleForm.county = "";
      }
      if (arry[0] != "全部" && arry[1] != "全部" && arry[2] == "全部") {
        this.ruleForm.provinces = arry[0];
        this.ruleForm.city = arry[1];
        this.ruleForm.county = "全部";
      }
      if (arry[0] != "全部" && arry[1] != "全部" && arry[2] != "全部") {
        this.ruleForm.provinces = arry[0];
        this.ruleForm.city = arry[1];
        this.ruleForm.county = arry[2];
      }
    },
    getlist() {
      getCustomerList({ ...this.pagination, ...this.ser }).then((res) => {
        if (res.code == 200) {
          this.productList = res.data.data;
          this.total = res.data.total;
          this.loading = false;
        }
      });
    },

    customer_clicks() {
      this.ser.balance_status='';
      this.ser.balance='';
      this.ser.customer_name = "";
      getCustomerList(this.pagination).then((res) => {
        if (res.code == 200) {
          this.productList = res.data.data;
          this.total = res.data.total;
        }
      });
    },
    customer_click(type) {
      if (type == 0) {
        this.pagination.per_page = 10;
        this.pagination.page = 1;
      }
      getCustomerList({ ...this.ser, ...this.pagination }).then((res) => {
        if (res.code == 200) {
          this.productList = res.data.data;
          this.total = res.data.total;
        }
      });
    },
    add_product() {
      this.title = "新增客户";
      this.isProduct = true;
      this.ruleForm = {
        customer_name: "",
        provinces: "",
        city: "",
        county: "",
        customer_address: "",
        account_executive_id:"",
        contact: "",
        contact_phone: "",
        remark: "",
        logistics:"",
        id: "",
      };
      this.selectedOptions = [];
      this.userlist();
      this.log_isticsCompany()
    },
    userlist(){
      getUserList({role_id_data: [1,2,3]}).then(res => {
        if (res.code == 200) {
          this.UserList = res.data.data
        }
      })
    },
    submitadd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          createCustomer(this.ruleForm).then((res) => {
            if (res.code == 200) {
              this.isProduct = false;
              this.$message.success("提交成功");
              this.getlist();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    set_product(row) {
      this.userlist();
      this.log_isticsCompany()
      this.ruleForm.customer_name= row.customer_name
      // this.ruleForm.provinces= row.provinces?row.provinces:''
      // this.ruleForm.city= row.city?row.city:''
      // this.ruleForm.county= row.county?
      this.ruleForm.customer_address= row.customer_address?row.customer_address:''
      this.ruleForm.source_user_id= row.source_user_id
      this.ruleForm.contact= row.contact?row.contact:""
      this.ruleForm.contact_phone= row.contact_phone?row.contact_phone:""
      this.ruleForm.remark= row.remark
      this.ruleForm.logistics= row.logistics
      this.ruleForm.account_executive_id=row.account_executive_id
      this.ruleForm.id= row.id
      var provinces, city, county;
      this.title = "客户编辑";
      this.isProduct = true;
      if (row.provinces && row.provinces != "全部") {
        provinces = TextToCode[row.provinces].code;
        if (row.city && row.city != "全部") {
          city = TextToCode[row.provinces][row.city].code;
          if (row.county && row.county != "全部") {
            console.log("wwe11");
            county = TextToCode[row.provinces][row.city][row.county].code;
          } else {
            console.log("wwee");
            county = "";
          }
        } else {
          city = null;
          county = null;
        }
      }
      if (provinces) {
        this.selectedOptions = [provinces, ""];
      }
      if (provinces && city) {
        this.selectedOptions = [provinces, city, ""];
      }
      if (provinces && city && county) {
        this.selectedOptions = [provinces, city, county];
      }
    },
    handleSizeChange(val) {
      console.log(val);
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pagination.page = val;
      this.getlist();
    },
    prev() {
      this.pagination.page = this.pagination.page - 1;
      this.getlist();
    },
    next() {
      console.log("ss");
      this.pagination.page = this.pagination.page + 1;
      this.getlist();
    },
  },
};
</script>

<style>
  .red {
    color: red;
  }
</style>
